﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace TVShow.Framework
{
	public class DisplayItem
	{
		Control control;

		public DisplayItem(Control Control) {
			this.control = Control;
		}

		public void Add(ILockRequester Requester, Control newControl) {
			if (Requester == Owner && control != null)
				control.Controls.Add(newControl);
		}

		public void Clear(ILockRequester Requester) {
			if (Requester == Owner && control != null) {
				control.Controls.Clear();
			}
		}

		public string Text {
			get {
				if (control != null)
					return control.Text;
				return "";
			}
			set {
				if (control != null)
					control.Text = value;
			}
		}

		ILockRequester Owner = null;
		public bool Locked {
			get {
				if (Owner != null)
					return true;
				else
					return false;
			}
		}

		/// <summary>
		/// Lock this resource. If the resource is currently locked by another object,
		/// an unlock will be requested. Returns true if the lock is successful (the caller
		/// can use the resource.) False if the lock is unsuccessful (the caller may NOT 
		/// use the resource.)
		/// If the owner asks to lock the same resource again, RequestUnlock will NOT be called.
		/// <para>
		/// Use HardLock to ask the current owner to release the item. If the current owner
		/// refuses the request, Lock will return false and the NewOwner will NOT get the lock.
		/// </para>
		/// </summary>
		/// <param name="NewOwner"></param>
		/// <param name="HardLock">Request that the current owner release the resource.</param>
		/// <returns></returns>
		public bool Lock(ILockRequester NewOwner) {
			if (Owner == NewOwner)
				return true;
			if (Locked)
				Unlock(NewOwner);
			if (Locked)
				return false;
			Owner = NewOwner;
			return true;
		}

		/// <summary>
		/// Unlock this display resource. If the owner of the resource requests the unlock,
		/// the resource is unlocked immediately. If another object requests it, the owner
		/// is given the opportunity to release the lock. If the release fails, or the owner
		/// refuses to unlock the object, false is returned. 
		/// </summary>
		/// <param name="Requester">Object requesting the unlock.</param>
		/// <returns>True if unlock was successful. False if not.</returns>
		public bool Unlock(ILockRequester Requester) {
			if (!Locked) return true;

			if (Owner.UnlockRequest(this))
				Owner = null;

			return !Locked;
		}

	}
}
